package edu.gzhu.guli.back.service.role;

import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Service;

import edu.gzhu.guli.core.common.ApplicationResult;
import edu.gzhu.guli.core.entity.Role;
import edu.gzhu.guli.core.entity.Role_;
import edu.gzhu.guli.core.repository.RoleRepository;
import lombok.AllArgsConstructor;

@Service
@AllArgsConstructor
public class RoleService {

  final RoleRepository roleRepository;
  final ModelMapper modelMapper;

  public ApplicationResult<List<RoleReadDto>> loadAllRole() {
    List<RoleReadDto> data = roleRepository.findAll()
        .stream()
        .map(it -> modelMapper.map(it, RoleReadDto.class))
        .collect(Collectors.toList());
    return ApplicationResult.succese(data);
  }

  // 创建用户角色
  public ApplicationResult<RoleReadDto> create(RoleCreateOrEditDto dto) {
    Optional<Role> check = roleRepository.findByName(dto.getName());
    if (check.isPresent())
      return ApplicationResult.failure("角色名：" + dto.getName() + "已存在");
    Role role = modelMapper.map(dto, Role.class);
    role = roleRepository.save(role);
    RoleReadDto data = modelMapper.map(role, RoleReadDto.class);
    return ApplicationResult.succese(data);
  }

  // 编辑用户角色
  public ApplicationResult<RoleReadDto> edit(Long roleId, RoleCreateOrEditDto dto) {
    Optional<Role> check = roleRepository.findById(roleId);
    if (!check.isPresent())
      return ApplicationResult.failure("未找到对应角色");
    Role role = check.get();
    check = roleRepository
        .findOne(builder -> builder.andNotEquals(Role_.NAME, dto.getName()).andEquals(Role_.ID, roleId).build());
    if (!check.isPresent())
      return ApplicationResult.failure("角色名：" + dto.getName() + "已存在");

    modelMapper.map(dto, role);
    role = roleRepository.save(role);
    RoleReadDto data = modelMapper.map(role, RoleReadDto.class);
    return ApplicationResult.succese(data);
  }

  private static Set<String> systemRoleName;

  static {
    systemRoleName = new HashSet<>();
    systemRoleName.add("ROOT");
    systemRoleName.add("ADMIN");
    systemRoleName.add("MEMBER");
  }

  // 删除用户角色
  public ApplicationResult<Object> delete(Long roleId) {
    Optional<Role> check = roleRepository.findById(roleId);
    if (!check.isPresent())
      return ApplicationResult.failure("未找到对应角色");
    Role role = check.get();
    if (systemRoleName.contains(role.getName()))
      return ApplicationResult.failure("无法删除系统自带的角色");
    roleRepository.delete(role);
    return ApplicationResult.succese();
  }

}
